//
//  WFDesignerDetailVC.m
//  谷居
//
//  Created by dllo on 16/7/1.
//  Copyright © 2016年 刘万方. All rights reserved.
//

#import "WFDesignerDetailVC.h"
#import "WFButtonImage.h"
#import "WFUIView.h"
#import "Masonry.h"
#import "WFTableView.h"
#import "WFMainTableView.h"
#import "WFCaseCell.h"
#import "WFDesignerDetailCell.h"
#import "WFDesignerScrollView.h"
#import "WFImageView.h"
#import "WFLabel.h"
#import "UIImageView+AFNetworking.h"
#import "MBProgressHUD.h"
#import "AFNetworking.h"

#import "WFProjectModel.h"
#import "WFUserModel.h"
#import "WFUserimageModel.h"
#import "MJRefresh.h"

#import "WFDGuideView.h"

//#import "WFInspirationView.h"
#define CONY _scrollView.contentOffset.y
@interface WFDesignerDetailVC ()<UITableViewDelegate, UITableViewDataSource, WFDesignerDetaolCellDelegate, UIScrollViewDelegate, WFCaseCellDelegate>

@property (nonatomic, retain) WFUIView *navigationView;



@property (nonatomic, retain) UIButton *leftButton;

@property (nonatomic, retain) UIButton *rightButton;


@property (nonatomic, retain) WFUIView *topView; /** 头部视图. */

@property (nonatomic, retain) NSMutableArray *caseArray;

@property (nonatomic, retain) WFUIView *fourButtonBaseView;

@property (nonatomic, assign) CGFloat centerY;

@property (nonatomic, retain) WFMainTableView *mainTableView;

@property (nonatomic, retain) WFDesignerScrollView *scrollView;



@property (nonatomic, retain) WFImageView * photoImageView;

@property (nonatomic, retain) WFLabel *nameLabel;

@property (nonatomic, retain) WFImageView *baseImageView;

@property (nonatomic, retain) UIButton *caseButton;

@property (nonatomic, retain) UIButton *guideButton;

@property (nonatomic, retain) UIButton *inspirationButton;

@property (nonatomic, retain) UIButton *shareButton;

@property (nonatomic, retain) NSMutableArray *projectArray;

@property (nonatomic, retain) NSMutableArray *userImageArray;

@property (nonatomic, retain) NSMutableArray *photoImageArray;

@property (nonatomic, assign) NSInteger start;
@property (nonatomic, retain) NSMutableArray *userArray;


@property (nonatomic, retain) WFDGuideView *guideView;

//@property (nonatomic, retain) WFInspirationView *insPirationView;

//@property (nonatomic, retain) UIScrollView *baseScrollView;

@end

@implementation WFDesignerDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
#pragma mark - 创建scrollView
    
    [self createScrollView];
#pragma mark - 创建上方头部视图
    [self createTopView];
    
#pragma mark - 创建主tableView;
    [self createMainTableView];
    

#pragma mark - 创建头部视图点击按钮底层View
    [self createFourButtonView];
    
#pragma mark - 先处理navigation
    /** 先处理navigationBar. */
    [self handleNavigation];
    
#pragma mark - 创建小菊花
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
#pragma mark - 进行网络请求
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:self.professionnalModel.realName];
    NSString *str = @"%E6%9C%A8%E6%9C%A8";
    NSString *url = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/user/%@/projects?start=0&count=10&user=%@", [self.professionnalModel.userName stringByAddingPercentEncodingWithAllowedCharacters:set], str];

    [self makeRequestWithUrl:url upDown:YES];
    
    
#pragma mark - 创建线程
    
//    [self createDispatch];
    
    
    
    // Do any additional setup after loading the view.
}

/** 网络请求. */

- (void)makeRequestWithUrl:(NSString *)url upDown:(BOOL)upDown {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   // http://api.guju.com.cn/v2/user/%E9%A1%BE%E6%82%A6/projects?start=0&count=10&user=%E6%9C%A8%E6%9C%A8
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (upDown) {
            NSArray *projectArray = [responseObject valueForKey:@"projects"];
            self.projectArray = [WFProjectModel baseModelByArray:projectArray];
            [self createUserAndImageArray];
        } else {
            NSArray *projecArray = [responseObject valueForKey:@"projects"];
            [self.projectArray addObjectsFromArray:projecArray];
            [self createUserAndImageArray];
        }
        
        [_mainTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
}
- (void)createUserAndImageArray {
    NSMutableArray *arr = [NSMutableArray array];
    
    for (WFProjectModel *temp in self.projectArray) {
        [arr addObject:temp.user];
        
    }
    [self.userArray removeAllObjects];
    self.userArray = [WFUserModel baseModelByArray:arr];
    
    
    [self.userImageArray removeAllObjects];
    for (WFUserModel *temp in self.userArray) {
        WFUserimageModel *imageModel = [[WFUserimageModel alloc] init];
        [imageModel setValuesForKeysWithDictionary:(NSDictionary *)temp.userImage];
        [self.userImageArray addObject:imageModel];
        [imageModel release];
    }
    
}

- (void)handleNavigation {
#pragma mark - 创建假的navigationbar
    _leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_leftButton];
    [_leftButton setBackgroundImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    [_leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.top.equalTo(self.view).offset(26);
        make.size.mas_equalTo(CGSizeMake(32, 32));
        
    }];
    [self.view bringSubviewToFront:_leftButton];
    [_leftButton addTarget:self action:@selector(clickLeftButton:) forControlEvents:UIControlEventTouchUpInside];
    _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_rightButton];
    [_rightButton setBackgroundImage:[UIImage imageNamed:@"分享黑.png"] forState:UIControlStateNormal];
    [_rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-16);
        make.top.equalTo(self.view).offset(26);
        make.size.equalTo(_leftButton);
        
    }];
    [_rightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view bringSubviewToFront:_rightButton];
    
    
}

#pragma 假button
- (void)clickLeftButton:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickRightButton:(UIButton *)button {
    NSLog(@"分享按钮");
    
    
}
/** 创建主tableView. */
- (void)createMainTableView {
    _mainTableView = [[WFMainTableView alloc] initWithFrame:CGRectMake(0, 260, SCREEN_WIDTH, SCREEN_HEIGHT - 40) style:UITableViewStylePlain];
    [_scrollView addSubview:_mainTableView];
    [_mainTableView release];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    _mainTableView.rowHeight = 240;
    
    _mainTableView.userInteractionEnabled = YES;
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    _mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
}

#pragma mark - 刷新的方法
- (void)refresh {
    self.start = 0;
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:self.professionnalModel.realName];
    NSString *str = @"%E6%9C%A8%E6%9C%A8";
    NSString *url = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/user/%@/projects?start=%ld&count=10&user=%@", [self.professionnalModel.userName stringByAddingPercentEncodingWithAllowedCharacters:set], self.start, str];
    [self makeRequestWithUrl:url upDown:YES];
    [_mainTableView.mj_header endRefreshing];
    [_mainTableView reloadData];
}

- (void)loadMore {
    self.start += 10;
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:self.professionnalModel.realName];
    NSString *str = @"%E6%9C%A8%E6%9C%A8";
    NSString *url = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/user/%@/projects?start=%ld&count=10&user=%@", [self.professionnalModel.userName stringByAddingPercentEncodingWithAllowedCharacters:set], self.start, str];
    [self makeRequestWithUrl:url upDown:NO];
    [_mainTableView.mj_footer endRefreshing];
    [_mainTableView reloadData];
}


#pragma mark - 创建scrollview

- (void)createScrollView {
    _scrollView = [[WFDesignerScrollView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
    [self.view addSubview:_scrollView];
    [_scrollView release];
    
    
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT + 220);
    _scrollView.bounces = NO;
    _scrollView.delegate = self;
//    _scrollView.userInteractionEnabled = NO;
}

/** 上方头部视图. */
- (void)createTopView {
    _topView = [[WFUIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 260)];
    [_scrollView addSubview:_topView];
    [_topView release];
    
#pragma mark - 在topView上添加控件.
    /** 在topView的上面添加控件. */
    [self createViewOfTopView];
    
}

/** topView上的控件. */
- (void)createViewOfTopView {
    _baseImageView = [[WFImageView alloc] init];
    [_topView addSubview:_baseImageView];
    [_baseImageView release];
    [_baseImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_topView);
        make.size.equalTo(_topView);
       
    }];
    [_baseImageView setImageWithURL:[NSURL URLWithString:_userImageModel.large] placeholderImage:nil];
    
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = CGRectMake(0, 0, SCREEN_WIDTH, _topView.frame.size.height);
    [_baseImageView addSubview:effectView];
    [effectView release];

    _photoImageView = [[WFImageView alloc] init];
    [_topView addSubview:_photoImageView];
    [_photoImageView release];
    [_photoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.center.equalTo(_topView);
        make.size.mas_equalTo(CGSizeMake(60, 60));
        
    }];
    _photoImageView.layer.cornerRadius = 30;
    _photoImageView.layer.masksToBounds = YES;
    _photoImageView.layer.borderWidth = 2;
    _photoImageView.layer.borderColor  = [UIColor whiteColor].CGColor;
    [_photoImageView setImageWithURL:[NSURL URLWithString:self.userImageModel.small] placeholderImage:nil];
    
    _nameLabel = [[WFLabel alloc] init];
    [_topView addSubview:_nameLabel];
    [_nameLabel release];
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_topView);
        make.top.equalTo(_photoImageView.mas_bottom).offset(20);
        make.height.mas_equalTo(@20);
        make.width.greaterThanOrEqualTo(@20);
        
        
    }];
    _nameLabel.text = self.professionnalModel.realName;
    _nameLabel.backgroundColor = [UIColor clearColor];
    _nameLabel.textColor = [UIColor whiteColor];
    [_nameLabel sizeToFit];

}

#pragma mark - 创建四个按钮的方法
/** 四个点击按钮. */
- (void)createFourButtonView {
    _fourButtonBaseView = [[WFUIView alloc] init];
    [_topView addSubview:_fourButtonBaseView];
    [_fourButtonBaseView release];
    [_fourButtonBaseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(_topView);
        make.height.mas_equalTo(40);
        
    }];
    
    
#pragma mark - 创建四个button
    _caseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_fourButtonBaseView addSubview:_caseButton];
    
    _guideButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_fourButtonBaseView addSubview:_guideButton];
    
//    _inspirationButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_fourButtonBaseView addSubview:_inspirationButton];
//    
//    _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_fourButtonBaseView addSubview:_shareButton];
//    
    
    [_caseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(@[_guideButton, _fourButtonBaseView]);
        make.left.equalTo(_fourButtonBaseView);
        make.height.equalTo(@[_fourButtonBaseView,_guideButton]);
        make.width.mas_equalTo(SCREEN_WIDTH / 2);
    
    }];
    [_guideButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_caseButton.mas_right);
        make.width.equalTo(@[_caseButton]);
    }];
    
//    [_inspirationButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(_guideButton.mas_right);
//        
//    }];
//    [_shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.right.equalTo(_fourButtonBaseView);
//    }];
//    
    
    [_caseButton setTitle:@"案例" forState:UIControlStateNormal];
    [_caseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [_caseButton setTitleColor:[UIColor lightTextColor] forState:UIControlStateHighlighted];

    [_guideButton setTitle:@"攻略" forState:UIControlStateNormal];
    [_guideButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
//    [_inspirationButton setTitle:@"灵感" forState:UIControlStateNormal];
//    [_inspirationButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    
//    [_shareButton setTitle:@"分享" forState:UIControlStateNormal];
//    [_shareButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    
    
    [_caseButton addTarget:self action:@selector(clickCaseButton:) forControlEvents:UIControlEventTouchUpInside];
    [_guideButton addTarget:self action:@selector(clickGuideButton:) forControlEvents:UIControlEventTouchUpInside];
//    [_inspirationButton addTarget:self action:@selector(clickInspirationButton:) forControlEvents:UIControlEventTouchUpInside];
//    [_shareButton addTarget:self action:@selector(clickShareButton:) forControlEvents:UIControlEventTouchUpInside];
//    
}


- (void)clickCaseButton:(UIButton *)button {
    NSLog(@"点击案例按钮. ");
    [_scrollView bringSubviewToFront:_mainTableView];
//    [self.view sendSubviewToBack:self.guideView];
}

- (void)clickGuideButton:(UIButton *)button {
    [_scrollView bringSubviewToFront:self.guideView];
}

- (void)clickInspirationButton:(UIButton *)button {
}
- (void)clickShareButton:(UIButton *)button {
    
}


#pragma mark - 创建tableView 的协议方法
/** tableView 的协议方法. */

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if (section == 0) {
//        return 0;
//    }else {
//        return 1;
//    }
//    return self.caseArray.count;
    NSLog(@"%ld", self.projectArray.count);
    return self.projectArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"designdetail";
//    WFDesignerDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    WFCaseCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[WFCaseCell  alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    
    }
    cell.projectModel = self.projectArray[indexPath.row];
    cell.userImageModel = self.userImageArray[indexPath.row];
    cell.delegate = self;
    cell.styleCell = YES;
//    cell.desDelegate = self;
    return cell;
}
- (void)tableViewReloadData {
    [_mainTableView reloadData];
}
#pragma mark - tableView的滑动

- (void)makeMainCellScrollWithY:(CGFloat)Y ScrollView:(UIScrollView *)scrollView {
    NSLog(@"Y inMain: %f", Y);
    
 }
#pragma mark - 懒加载

- (NSMutableArray *)projectArray {
    if (_projectArray == nil) {
        _projectArray = [[NSMutableArray array] retain];
    }
    return _projectArray;
}

//- (NSMutableArray *)imageArray {
//    if (_imageArray == nil) {
//        _imageArray = [[NSMutableArray array] retain];
//    }
//    return _imageArray;
//}

- (NSMutableArray *)photoImageArray {
    if (_photoImageArray == nil) {
        _photoImageArray = [[NSMutableArray array] retain];
    }
    return _photoImageArray;
}
- (NSMutableArray *)userArray {
    if (_userArray == nil) {
        _userArray = [[NSMutableArray array] retain];
    }
    return _userArray;
}
- (void)createDispatch {
    dispatch_queue_t myQueue = dispatch_queue_create("topQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t mianQueue = dispatch_get_main_queue();
    dispatch_sync(myQueue, ^{
       /** 创建菊花. */
        /** 请求数据. */
        dispatch_sync(mianQueue, ^{
           /** 创建tableView. */;
            
        });
        
    });
}



#pragma mark - 懒加载
- (NSMutableArray *)caseArray {
    if (_caseArray == nil) {
        _caseArray = [[NSMutableArray array] retain];
    }
    return _caseArray;
}

- (WFDGuideView *)guideView {
    if (!_guideView) {
        _guideView = [[WFDGuideView alloc] initWithFrame:CGRectMake(0, 260, SCREEN_WIDTH, SCREEN_HEIGHT - 40) WithName:self.professionnalModel.userName];
        [_scrollView addSubview:_guideView];
        [_guideView release];
        NSLog(@"username: %@", self.professionnalModel.userName);
    }
    return _guideView;
}

//- (WFInspirationView *)insPirationView {
//    if (!_insPirationView) {
//        _insPirationView = [[WFInspirationView alloc] initWithFrame:CGRectMake(0, 260, SCREEN_WIDTH, SCREEN_HEIGHT)];
//        [_scrollView addSubview:_insPirationView];
//        [_insPirationView release];
////        _insPirationView.backgroundColor = [UIColor redColor];
//    }
//    return _insPirationView;
//    
//}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
